package com.bs.manager04.utils.aop;

import cn.hutool.http.server.HttpServerRequest;
import com.bs.manager04.entity.User;
import com.bs.manager04.utils.RedisUtils;
import com.bs.manager04.utils.TokenUtils;
import com.bs.manager04.utils.auth.Auth;
import com.bs.manager04.utils.exception.NoAuthException;
import com.bs.manager04.utils.exception.NotUserNullException;
import com.sun.corba.se.spi.ior.ObjectKey;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author 小姚
 * @pakeageName:com.bs.manager04.utils.aop
 * @ClassName:AuthAspectAop
 * @Descirption:
 * @data 2022/12/17 21:34
 */
//将该类交给spring容器管理
/*@Component
//表明该类是切面类
@Aspect*/
public class AuthAspectAop {

    @Resource
    HttpSession session;

    @Resource
    HttpServletRequest request;

    @Resource
    RedisUtils utils;

    @Around("execution(* com.bs.manager04.controller.*.*(..)) && @annotation(com.bs.manager04.utils.auth.Auth)")
    public Object getAround(ProceedingJoinPoint point) throws Throwable {
        String token = request.getHeader(TokenUtils.TOKEN_NAME);
        User user =(User) utils.get(token);
        Object o=null;
        if(user!=null){
            //用户登录成功后，再次设置用户的失效时间
            utils.expire(token,TokenUtils.TOKEN_TIME);
            Signature signature = point.getSignature();
            MethodSignature methodSignature=(MethodSignature) signature;
            Method method = methodSignature.getMethod();
            Auth auth = method.getDeclaredAnnotation(Auth.class);
            if(auth!=null){
                String value = auth.value();
                if(user.getPremission().contains(value)){
                   o=point.proceed();
                }else{
                    throw new NoAuthException("你没有访问的权限，请联系管理员");
                }
            }
        }else{
            throw new NotUserNullException("你还未登录，请确认登录后再访问");
        }
return o;
    }
}
